package shujia.day18.tcpdemo4;

import shujia.day18.DateUtil;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class ClientThread extends Thread {

    private Socket s;

    public ClientThread(Socket socket) {
        this.s = socket;
    }

    @Override
    public void run() {
        //在服务器端获取客户端的信息
        InetAddress inetAddress = s.getInetAddress();
        String ip = inetAddress.getHostAddress();
        File file1 = new File("F:\\users\\" + ip + "\\" + System.currentTimeMillis());
        file1.mkdirs();

        try {
            //获取通道中的输入流对象，获取客户端发送的数据
            InputStream inputStream = s.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);

            //获取通道中的输出流对象，给客户端写反馈
            OutputStream outputStream = s.getOutputStream();

            DataInputStream dis = new DataInputStream(s.getInputStream());
            String fileName = dis.readUTF(); // 读取文件名
            System.out.println("接收到的文件名: " + fileName);

            File file2 = new File(file1, fileName);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));

            byte[] bytes = new byte[1024];
            int length = 0;
            while ((length = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, length);
                bos.flush();
            }
            outputStream.write("文件上传成功！！".getBytes());
            outputStream.flush();


            bos.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
